<template>
  <div>
    <!-- 顶部导航 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>权限管理</el-breadcrumb-item>
      <el-breadcrumb-item>角色列表</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- 卡片 -->
    <el-card>
      <!-- 添加角色按钮 -->
      <el-row>
        <el-col>
          <el-button type="primary" @click="AdddialogVisible = true">添加角色列表</el-button>
        </el-col>
      </el-row>
      <!-- 角色列表区域 -->
      <el-table :data="roleList" border>
        <!-- 添加展开列 -->
        <el-table-column type="expand">
          <template v-slot:default="scope">
            <el-row
              :class="['bdbottom',i1 === 0 ? 'bdtop':'','vcenter']"
              v-for="(item1,i1) in scope.row.children"
              :key="item1.id"
            >
              <!-- 一级列表 -->
              <el-col :span="5">
                <el-tag closable @close="removeRightById(scope.row,item1.id)">{{item1.authName}}</el-tag>
                <i class="el-icon-caret-right"></i>
              </el-col>
              <!-- 二级列表 -->
              <el-col :span="19">
                <el-row
                  v-for="(item2,i2) in item1.children"
                  :key="item2.id"
                  :class="[i2 === 0 ? '':'bdtop','vcenter']"
                >
                  <el-col :span="6">
                    <el-tag
                      type="success"
                      closable
                      @close="removeRightById(scope.row,item2.id)"
                    >{{item2.authName}}</el-tag>
                    <i class="el-icon-caret-right"></i>
                  </el-col>
                  <el-col :span="18">
                    <el-tag
                      v-for="(item3) in item2.children"
                      :key="item3.id"
                      closable
                      @close="removeRightById(scope.row,item3.id)"
                      type="warning"
                    >{{item3.authName}}</el-tag>
                  </el-col>
                </el-row>
              </el-col>
              <!-- 第二第三级结束 -->
            </el-row>
            <!-- <pre>
               {{scope.row}}
            </pre>-->
          </template>
        </el-table-column>
        <el-table-column type="index"></el-table-column>
        <el-table-column label="角色名称" prop="roleName"></el-table-column>
        <el-table-column label="角色描述" prop="roleDesc"></el-table-column>
        <el-table-column label="操作" width="300px">
          <template v-slot:default="scope">
            <el-button
              size="mini"
              type="primary"
              icon="el-icon-edit"
              @click="editdialog(scope.row.id)"
            >编辑</el-button>
            <el-button
              size="mini"
              type="danger"
              icon="el-icon-delete"
              @click="removeuser(scope.row.id)"
            >删除</el-button>
            <el-button
              size="mini"
              type="warning"
              icon="el-icon-setting"
              @click="RolesDialog(scope.row)"
            >分配权限</el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-card>
    <!-- 分配权限对话框 -->
    <el-dialog
      title="分配权限"
      :visible.sync="RolesDialogVisible"
      width="50%"
      @close="RolesDialogClose"
    >
      <!-- <span>这是一段信息</span> -->
      <el-tree
        show-checkbox
        node-key="id"
        :data="treeList"
        :props="treeProps"
        default-expand-all
        ref="treeref"
        :default-checked-keys="defkeys"
      ></el-tree>
      <span slot="footer" class="dialog-footer">
        <el-button @click="RolesDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="AllRolesDialog">确 定</el-button>
      </span>
    </el-dialog>
    <!-- 添加角色对话框 -->
    <el-dialog title="添加角色" :visible.sync="AdddialogVisible" width="50%" @close="AddRolesClosed">
      <el-form
        :model="Addrolesform"
        :rules="Addrolesformrules"
        ref="AddrolesformRef"
        label-width="100px"
      >
        <el-form-item label="角色名称" prop="roleName">
          <el-input v-model="Addrolesform.roleName"></el-input>
        </el-form-item>
        <el-form-item label="角色描述" prop="roleDesc">
          <el-input v-model="Addrolesform.roleDesc"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="AdddialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="AddRolesUser">确 定</el-button>
      </span>
    </el-dialog>
    <!-- 编辑修改对话框 -->
    <el-dialog title="添加角色" :visible.sync="editdialogVisible" width="50%" @close="editDialogClosed">
      <el-form
        :model="editrolesform"
        :rules="editrolesformrules"
        ref="editrolesformRef"
        label-width="100px"
      >
        <el-form-item label="角色名称" prop="roleName">
          <el-input v-model="editrolesform.roleName"></el-input>
        </el-form-item>
        <el-form-item label="角色描述" prop="roleDesc">
          <el-input v-model="editrolesform.roleDesc"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="editdialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="editRolesUser">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>
<script>
export default {
  data() {
    return {
      roleList: [],
      treeList: [],
      AddRoles: false,
      RolesDialogVisible: false,
      AdddialogVisible: false,
      editdialogVisible: false,
      Addrolesform: {
        roleName: '',
        roleDesc: ''
      },
      editrolesform: {},
      treeProps: {
        children: 'children',
        label: 'authName'
      },
      // 默认选中的内容
      defkeys: [],
      RoleId: '',
      // 添加表单验证
      Addrolesformrules: {
        roleName: [
          { required: true, message: '请输入活动名称', trigger: 'blur' }
        ],
        roleDesc: [
          { required: true, message: '请输入活动名称', trigger: 'blur' }
        ]
      },
      editrolesformrules: {
        roleName: [
          { required: true, message: '请输入活动名称', trigger: 'blur' }
        ],
        roleDesc: [
          { required: true, message: '请输入活动名称', trigger: 'blur' }
        ]
      }
    }
  },
  created() {
    this.getRoleList()
  },
  methods: {
    async getRoleList() {
      const { data: res } = await this.$http.get('roles')
      //   console.log(res)
      if (res.meta.status !== 200) return this.$message.error('获取失败！')
      // this.$message.success('获取成功！')
      this.roleList = res.data
    },
    async removeRightById(role, rightId) {
      // 确认弹框是否删除
      const confirmResult = await this.$confirm(
        '此操作将永久删除该文件, 是否继续?',
        '提示',
        {
          confirmButtonText: '确认删除',
          cancelButtonText: '取消',
          type: 'warning'
        }
      ).catch(err => err)
      if (confirmResult !== 'confirm') {
        return this.$message.info('已经取消删除')
      }
      console.log('确认了删除')
      const { data: res } = await this.$http.delete(
        `roles/${role.id}/rights/${rightId}`
      )
      if (res.meta.status !== 200) {
        return this.$message.error('删除角色权限失败')
      }
      role.children = res.data
    },
    // 点击删除用户
    async removeuser(id) {
      const confirmReslut = await this.$confirm(
        '此操作将永久删除该用户, 是否继续?',
        '提示',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }
      ).catch(err => err)
      if (confirmReslut !== 'confirm') {
        return this.$message.info('已经取消了删除')
      }
      const { data: res } = await this.$http.delete('roles/' + id)
      if (res.meta.status !== 200) return this.$message.error('删除失败')
      this.$message.success('删除成功！')
      //   console.log(res)
      this.getRoleList()
    },
    // 分配权限获取数据
    async RolesDialog(role) {
      this.RoleId = role.id
      const { data: res } = await this.$http.get('rights/tree')
      if (res.meta.status !== 200) return this.$message.error('获取权限失败')
      this.$message.success('获取权限成功')
      this.treeList = res.data
      this.getleafKeys(role, this.defkeys)
      this.RolesDialogVisible = true
    },
    // 通过递归的形式 获取 三级分类的id 保存到defkeys
    getleafKeys(node, arr) {
      // 如果当前没有children节点 代表这是三级分类
      if (!node.children) {
        return arr.push(node.id)
      }
      node.children.forEach(item => {
        this.getleafKeys(item, arr)
      })
    },
    // 监听分配关闭对话框
    RolesDialogClose() {
      this.defkeys = []
    },
    async AllRolesDialog() {
      // 全选及半选
      const keys = [
        ...this.$refs.treeref.getCheckedKeys(),
        ...this.$refs.treeref.getHalfCheckedKeys()
      ]
      const idstr = keys.join(',')
      console.log(idstr)

      const { data: res } = await this.$http.post(
        `roles/${this.RoleId}/rights`,
        { rids: idstr }
      )
      if (res.meta.status !== 200) return this.$message.error('分配权限失败')

      this.$message.success('分配权限成功')
      this.getRoleList()
      // 关闭对话框
      this.RolesDialogVisible = false
    },
    // 添加角色
    AddRolesUser() {
      this.$refs.AddrolesformRef.validate(async valid => {
        if (!valid) return
        const { data: res } = await this.$http.post('roles', this.Addrolesform)
        if (res.meta.status !== 201) {
          return this.$message.error('添加失败')
        }
        this.$message.success('添加成功!')
        this.AdddialogVisible = false
        this.getRoleList()
      })
    },
    AddRolesClosed() {
      this.$refs.AddrolesformRef.resetFields()
    },
    // 修改编辑角色 获取id
    async editdialog(id) {
      const { data: res } = await this.$http.get('roles/' + id)
      console.log(res.data)
      this.editrolesform = res.data
      this.editdialogVisible = true
    },
    editDialogClosed() {
      this.$refs.editrolesformRef.resetFields()
    },
    editRolesUser() {
      this.$refs.editrolesformRef.validate(async valid => {
        if (!valid) return false
        const { data: res } = await this.$http.put(
          'roles/' + this.editrolesform.roleId,
          {
            roleName: this.editrolesform.roleName,
            roleDesc: this.editrolesform.roleDesc
          }
        )
        if (res.meta.status !== 200) {
          return this.$message.error('修改失败')
        }
        this.$message.success('修改成功')
        this.editdialogVisible = false
        this.getRoleList()
      })
    }
  }
}
</script>
<style lang="less" scoped>
.el-tag {
  margin: 7px;
}
.bdtop {
  border-top: 1px solid #eee;
}
.bdbottom {
  border-bottom: 1px solid #eee;
}
.vcenter {
  display: flex;
  align-items: center;
}
</style>
